<script setup lang="ts">
import {
  userData,
  genData,
  tqType
} from "@/views/marketForecast/loadForecasting/testData";
import VChart from "@/views/monitor/server/components/VChart.vue";
import { computed, onMounted, reactive, ref } from "vue";
import moment from "moment";
import { getVppUserListAll } from "@/api/vppUser";
import { Grid, RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm, ElMessage } from "element-plus";
import { getMarketPriceTrends, getNwpTrends } from "@/api/marketPriceTrends";
import { timeSlot, dayRangeArray } from "@/utils";
const loading = ref(false);
const activeUserId = ref(null);
const activeName = ref("first");
const tqData = reactive({
  data: tqType,
  activeTq: "dbwd",
  datas: [],
  chartsAndTData: []
});
// const activeTq = ref("dbwd");
const allUser = reactive({
  data: userData
});
const users = computed(() => {
  if (queryForm.data.activeVppId) {
    let parent = userData.find(item => item.id === queryForm.data.activeVppId);
    if (parent.children) {
      return parent.children;
    } else {
      return [];
    }
  } else {
    return [];
  }
});
const terms = computed(() => {
  if (queryForm.data.activeUserId) {
    let parent = users.value.find(
      item => item.id === queryForm.data.activeUserId
    );
    if (parent.children) {
      return parent.children;
    } else {
      return [];
    }
  } else {
    return [];
  }
});
const vppChange = () => {
  queryForm.data.activeUserId = undefined;
  queryForm.data.activeTermId = undefined;
};
const userChange = () => {
  queryForm.data.activeTermId = undefined;
  queryForm.data.activeSbId = undefined;
};
const queryForm = reactive({
  data: {
    activeVppId: undefined,
    activeUserId: undefined,
    activeTermId: undefined,
    activeSbId: undefined,
    activeTime: []
  }
});
const start = ref(0);
const end = ref(100);
const options = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    min: 1000
  },
  series: [
    {
      name: "预测数据",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const options2 = ref({
  title: {
    text: "数值天气预报",
    left: "10%"
  },
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    min: "dataMin"
  },
  series: [
    {
      name: "温度",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const init = async () => {
  // let res = await getVppUserListAll();
  // allUser.data = res.map(i => ({ ...i, id: i.id + "" }));
  queryForm.data.activeTime = [
    moment().subtract("day", -1).subtract("day", 3).format("YYYY-MM-DD"),
    moment().subtract("day", -1).format("YYYY-MM-DD")
  ];
  // queryForm.data.activeTime = ["2024-04-09", "2024-04-30"];
  // if (queryForm.data.activeUserId) {
  //   loading.value = true;
  //   let data = await getMarketPriceTrends({
  //     marketId: queryForm.data.activeUserId,
  //     begin: queryForm.data.activeTime[0],
  //     end: queryForm.data.activeTime[1]
  //   });
  //   dataFormat(data);
  // } else {
  //   dataFormat([]);
  // }
  // if (queryForm.data.activeUserId) {
  //   let data = await getNwpTrends({
  //     locationId: queryForm.data.activeUserId,
  //     begin: queryForm.data.activeTime[0],
  //     end: queryForm.data.activeTime[1]
  //   });
  //   dataFormatTwo(data);
  //   loading.value = false;
  // } else {
  //   dataFormatTwo([]);
  // }
};
const setTqData = () => {
  tqData.datas = [];
  tqData.data.forEach((item, index) => {
    let data = null;
    if (index === 0) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        20,
        30
      );
    }
    if (index === 1) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        70,
        100
      );
    }
    if (index === 2) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        20,
        30
      );
    }
    if (index === 3) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        0.1,
        1
      );
    }
    if (index === 4) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        20,
        30
      );
    }
    if (index === 5) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        20,
        30
      );
    }
    if (index === 6) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        20,
        30
      );
    }
    if (index === 7) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        2,
        10
      );
    }
    if (index === 8) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        0,
        90
      );
    }
    if (index === 9) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        0,
        100
      );
    }
    if (index === 10) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        10,
        20
      );
    }
    if (index === 11) {
      data = genData(
        queryForm.data.activeTime[0],
        queryForm.data.activeTime[1],
        10,
        20
      );
    }
    tqData.datas.push(data);
  });
  tqData.datas.forEach(i => {
    tqData.chartsAndTData.push(dataFormatCurrent(i));
  });
  let index = tqData.data.findIndex(i => i.key === tqData.activeTq);
  let current = tqData.chartsAndTData[index];
  options2.value.dataZoom[0].start = current.start;
  options2.value.dataZoom[0].end = current.end;
  options2.value.dataZoom[1].start = current.start;
  options2.value.dataZoom[1].end = current.end;
  options2.value.series[0].name = tqData.data[index].name;
  options2.value.series[0].data = current.showData;
  options2.value.xAxis.data = current.xData;
  tqData.data.forEach((item, index) => {
    showData.data.forEach(z => {
      z[item.key] = "";
    });
  });
  tqData.data.forEach((item, index) => {
    let currentKey = item.key;
    let currentData = tqData.chartsAndTData[index];
    showData.data.forEach(z => {
      z[currentKey] = currentData.mapData[z.label];
    });
  });
};
const currenTabChange = () => {
  let index = tqData.data.findIndex(i => i.key === tqData.activeTq);
  let current = tqData.chartsAndTData[index];
  options2.value.dataZoom[0].start = start.value;
  options2.value.dataZoom[0].end = end.value;
  options2.value.dataZoom[1].start = start.value;
  options2.value.dataZoom[1].end = end.value;
  options2.value.series[0].name = tqData.data[index].name;
  options2.value.series[0].data = current.showData;
  options2.value.xAxis.data = current.xData;
};
const search = async () => {
  if (
    (queryForm.data.activeVppId || queryForm.data.activeUserId) &&
    queryForm.data.activeTime &&
    queryForm.data.activeTime.length
  ) {
    loading.value = true;
    dataFormat(
      genData(queryForm.data.activeTime[0], queryForm.data.activeTime[1])
    );

    // let data2 = await getNwpTrends({
    //   locationId: queryForm.data.activeUserId,
    //   begin: queryForm.data.activeTime[0],
    //   end: queryForm.data.activeTime[1]
    // });
    // dataFormatTwo(data2);
    loading.value = false;
  } else {
    ElMessage({
      message: "请设置查询条件",
      type: "error"
    });
  }
};
const resetQuery = () => {
  queryForm.data = {
    activeVppId: undefined,
    activeUserId: undefined,
    activeTermId: undefined,
    activeSbId: undefined,
    activeTime: [
      moment().subtract("day", -1).subtract("day", 3).format("YYYY-MM-DD"),
      moment().subtract("day", -1).format("YYYY-MM-DD")
    ]
  };
};
const times = ref(timeSlot(15));
const keys = ref(
  Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`)
);
const showData = reactive({
  data: []
});
const dataFormatCurrent = data => {
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0],
      queryForm.data.activeTime[1]
    );
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    let item = {};
    item.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item[key] = null;
    });
    item.dataType = 1;
    allData.push(item);
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });

  let oneData = allData.filter(i => i.dataType === 1);
  let start = 0;
  let end = 100;
  let isd = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
    });
  });
  start = (1 - 96 / xData.length) * 100;
  let showData = [];
  let mapData = {};
  xData.forEach((item, index) => {
    let v = {
      label: item,
      value: isd[index].value
      // value2: tsd[index].value
    };
    showData.push(v);
    mapData[item] = isd[index].value;
  });
  showData.sort((a, b) => {
    return Date.parse(b.label) - Date.parse(a.label);
  });
  return {
    xData: xData,
    showData: showData,
    start: start,
    end: end,
    mapData: mapData
  };
};
const dataFormat = data => {
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0],
      queryForm.data.activeTime[1]
    );
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    let item = {};
    item.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item[key] = null;
    });
    item.dataType = 1;
    allData.push(item);
    let item2 = {};
    item2.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item2[key] = null;
    });
    item2.dataType = 2;
    allData.push(item2);
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });

  let oneData = allData.filter(i => i.dataType === 1);
  // let twoData = allData.filter(i => i.dataType === 2);
  let isd = [];
  // let tsd = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
    });
  });
  start.value = (1 - 96 / xData.length) * 100;
  options.value.xAxis.data = xData;
  options.value.dataZoom[0].start = start.value;
  options.value.dataZoom[1].start = start.value;
  options.value.dataZoom[0].end = end.value;
  options.value.dataZoom[1].end = end.value;
  // twoData.forEach(i => {
  //   times.value.forEach((z, index) => {
  //     tsd.push({
  //       value: i[keys.value[index]]
  //     });
  //   });
  // });
  options.value.series[0].data = isd;
  // options.value.series[1].data = tsd;
  showData.data = [];
  xData.forEach((item, index) => {
    let v = {
      label: item,
      value: isd[index].value
      // value2: tsd[index].value
    };
    showData.data.push(v);
  });
  showData.data.sort((a, b) => {
    return Date.parse(a.label) - Date.parse(b.label);
  });
  setTqData();
};

const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];
const dataZoomEvent = e => {
  if (e.batch && e.batch.length) {
    start.value = e.batch[0].start;
    end.value = e.batch[0].end;
  } else {
    start.value = e.start;
    end.value = e.end;
  }
  options.value.dataZoom[0].start = start.value;
  options.value.dataZoom[1].start = start.value;
  options.value.dataZoom[0].end = end.value;
  options.value.dataZoom[1].end = end.value;

  options2.value.dataZoom[0].start = start.value;
  options2.value.dataZoom[1].start = start.value;
  options2.value.dataZoom[0].end = end.value;
  options2.value.dataZoom[1].end = end.value;
};
const defaultColums = reactive({
  data: tqData.data
});
const colums = reactive({
  data: tqData.data
});
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.key) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.key) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  init();
  checkedCities.value = colums.data.map(item => item.key);
});
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-form :inline="true" :model="queryForm.data" label-width="0px">
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeVppId"
            placeholder="选择场站"
            style="width: 240px"
            @change="vppChange"
          >
            <el-option
              v-for="item in allUser.data"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryForm.data.activeUserId"
            placeholder="选择用户"
            style="width: 240px"
            @change="userChange"
          >
            <el-option
              v-for="item in users"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryForm.data.activeTime"
            unlink-panels
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            date-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
          />
        </el-form-item>
        <el-form-item class="ml-[10px]">
          <el-button type="primary" :icon="Search" @click="search"
            >查询</el-button
          >
          <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="图表" name="first">
          <div class="w-full h-1/2" style="min-height: 600px">
            <v-chart :options="options" @dataZoom="dataZoomEvent" />
          </div>
          <div
            class="w-full h-1/2 mt-[20px] flex flex-col"
            style="min-height: 600px"
          >
            <el-tabs v-model="tqData.activeTq" @tab-change="currenTabChange">
              <el-tab-pane
                v-for="item in tqData.data"
                :key="item.name"
                :label="item.name"
                :name="item.key"
              />
            </el-tabs>
            <div class="w-full flex-1">
              <v-chart :options="options2" @dataZoom="dataZoomEvent" />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second">
          <div class="w-full">
            <div class="w-full flex justify-end">
              <el-button-group class="ml-4">
                <el-popover placement="bottom" :width="200" trigger="click">
                  <template #reference>
                    <el-button type="primary" :icon="Grid" />
                  </template>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <div class="group-box w-full max-h-[240px] overflow-y-auto">
                    <el-checkbox-group
                      v-model="checkedCities"
                      class="columns-show-group"
                      @change="handleCheckedCitiesChange"
                    >
                      <el-checkbox
                        v-for="item in defaultColums.data"
                        :key="item.key"
                        :label="item.key"
                        >{{ item.name }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </div>
                </el-popover>
              </el-button-group>
            </div>
            <el-table :data="showData.data">
              <el-table-column label="时间" prop="label" />
              <el-table-column label="预测数据" prop="value" />
              <el-table-column
                v-for="item in colums.data"
                :key="item.key"
                :label="item.name"
                :prop="item.key"
              />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
